package com.jhy.ws.interceptor;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaTokenConsts;
import cn.hutool.extra.servlet.ServletUtil;
import com.jhy.core.domain.LoginUser;
import com.jhy.core.helper.LoginHelper;
import com.jhy.core.utils.Check;
import com.jhy.core.utils.ServletUtils;
import com.jhy.core.utils.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class WebSocketInterceptor implements HandshakeInterceptor {
    /**
     * websocket 连接前执行 用于判断是否允许握手
     * 可用于校验token，校验通过返回true，校验不通过返回false
     * **/
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        HttpServletRequest servletRequest = ServletUtils.getRequest();
        String authorization = servletRequest.getHeader("Authorization");
        Map<String, String[]> parameterMap = servletRequest.getParameterMap();
        // 如果请求头没取到 尝试从param取
        if (Check.isEmpty(authorization) && Check.isNoEmpty(parameterMap.get("Authorization"))){
            authorization = parameterMap.get("Authorization")[0];
        }
        String tokenPrefix = SaManager.getConfig().getTokenPrefix();
        String token = authorization.replace(tokenPrefix + SaTokenConsts.TOKEN_CONNECTOR_CHAT, "");
        Object loginIdByToken = StpUtil.getLoginIdByToken(token);
        if (loginIdByToken == null) {
            // 无效token
            return false;
        }
        attributes.put("loginId", loginIdByToken);
        attributes.put("token", token);
        attributes.put("userName", LoginHelper.getUsername());
        attributes.put("userId", LoginHelper.getUserId());
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
